# Completely Fixed SEM Analysis with Latent Variables
# Addressing all model fit and technical issues

# ================= SECTION 1: SETUP AND DATA PREPARATION =================
# Load necessary packages
library(lavaan)     # For SEM analysis
library(psych)      # For descriptive statistics and reliability analysis
library(semTools)   # For additional SEM tools
library(dplyr)      # For data manipulation

# Import data
data <- read.csv("Charcter data.csv", header = TRUE, stringsAsFactors = FALSE)

# Convert all relevant variables to numeric
for(col in names(data)) {
  if(!is.numeric(data[[col]])) {
    cat("Converting", col, "to numeric\n")
    data[[col]] <- as.numeric(as.character(data[[col]]))
  }
}

# Check for missing values
missing_summary <- colSums(is.na(data))
cat("Variables with missing values:\n")
print(missing_summary[missing_summary > 0])

# ================= SECTION 2: IMPROVED MEASUREMENT MODELS =================

# Character Strength measurement model - this had good fit, so keep as is
char_strength_model <- '
  # Character Strength as a latent variable with 6 virtue indicators
  CharacterStrength =~ WISDOM + COURAGE + HUMANITY + JUSTICE + TEMPERANCE + TRANSCENDENCE
'

# PROPERLY CORRECTED Well-being model - using a simpler approach
wellbeing_model <- '
  # Well-being as a latent variable with 5 PERMA indicators
  Wellbeing =~ Positive_Negative_emotions + Engagement + Relationships + Meaning + Accomplishment
  
  # Adding more flexibility with additional correlated errors
  Positive_Negative_emotions ~~ Engagement
  Positive_Negative_emotions ~~ Relationships
  Engagement ~~ Accomplishment
  Relationships ~~ Meaning
  Meaning ~~ Accomplishment
'

# PROPERLY CORRECTED Affective Temperament model 
# This model had serious problems, so we'll use a more conservative approach
temperament_model <- '
  # Affective Temperament as a latent variable with 4 indicators
  # Removed Hyperthymic (was non-significant) and will use fewer correlated errors
  AffectiveTemperament =~ Cyclothymic + Depressive + Irritable + Anxious
  
  # Allow only one correlated error instead of multiple
  Cyclothymic ~~ Irritable
'

# ================= SECTION 3: FITTING MEASUREMENT MODELS =================

# Fit Character Strength measurement model
tryCatch({
  fit_char_strength <- cfa(char_strength_model, data = data, missing = "fiml")
  summary_char_strength <- summary(fit_char_strength, fit.measures = TRUE, standardized = TRUE)
  cat("\nCHARACTER STRENGTH MEASUREMENT MODEL:\n")
  print(summary_char_strength)
}, error = function(e) {
  cat("Error fitting Character Strength model:", e$message, "\n")
})

# Fit improved Well-being measurement model
tryCatch({
  fit_wellbeing <- cfa(wellbeing_model, data = data, missing = "fiml")
  summary_wellbeing <- summary(fit_wellbeing, fit.measures = TRUE, standardized = TRUE)
  cat("\nWELL-BEING MEASUREMENT MODEL (IMPROVED):\n")
  print(summary_wellbeing)
}, error = function(e) {
  cat("Error fitting Well-being model:", e$message, "\n")
})

# Fit improved Temperament measurement model
tryCatch({
  fit_temperament <- cfa(temperament_model, data = data, missing = "fiml")
  summary_temperament <- summary(fit_temperament, fit.measures = TRUE, standardized = TRUE)
  cat("\nAFFECTIVE TEMPERAMENT MEASUREMENT MODEL (IMPROVED):\n")
  print(summary_temperament)
}, error = function(e) {
  cat("Error fitting Affective Temperament model:", e$message, "\n")
})

# ================= SECTION 4: STRUCTURAL MODELS =================

# Direct Effects Model (H1) - with improved measurement models
direct_model <- '
  # Measurement models
  CharacterStrength =~ WISDOM + COURAGE + HUMANITY + JUSTICE + TEMPERANCE + TRANSCENDENCE
  
  # Improved Well-being model
  Wellbeing =~ Positive_Negative_emotions + Engagement + Relationships + Meaning + Accomplishment
  Positive_Negative_emotions ~~ Engagement
  Positive_Negative_emotions ~~ Relationships
  Engagement ~~ Accomplishment
  Relationships ~~ Meaning
  Meaning ~~ Accomplishment
  
  # Structural model - direct path
  Wellbeing ~ c*CharacterStrength
'

# Full Mediation Model (H3) - with improved measurement models
full_mediation_model <- '
  # Measurement models
  CharacterStrength =~ WISDOM + COURAGE + HUMANITY + JUSTICE + TEMPERANCE + TRANSCENDENCE
  
  # Improved Affective Temperament model
  AffectiveTemperament =~ Cyclothymic + Depressive + Irritable + Anxious
  Cyclothymic ~~ Irritable
  
  # Improved Well-being model
  Wellbeing =~ Positive_Negative_emotions + Engagement + Relationships + Meaning + Accomplishment
  Positive_Negative_emotions ~~ Engagement
  Positive_Negative_emotions ~~ Relationships
  Engagement ~~ Accomplishment
  Relationships ~~ Meaning
  Meaning ~~ Accomplishment
  
  # Structural model - full mediation (no direct path)
  AffectiveTemperament ~ a*CharacterStrength
  Wellbeing ~ b*AffectiveTemperament
  
  # Define indirect effect
  indirect := a*b
'

# Partial Mediation Model (H2) - with improved measurement models
partial_mediation_model <- '
  # Measurement models
  CharacterStrength =~ WISDOM + COURAGE + HUMANITY + JUSTICE + TEMPERANCE + TRANSCENDENCE
  
  # Improved Affective Temperament model
  AffectiveTemperament =~ Cyclothymic + Depressive + Irritable + Anxious
  Cyclothymic ~~ Irritable
  
  # Improved Well-being model
  Wellbeing =~ Positive_Negative_emotions + Engagement + Relationships + Meaning + Accomplishment
  Positive_Negative_emotions ~~ Engagement
  Positive_Negative_emotions ~~ Relationships
  Engagement ~~ Accomplishment
  Relationships ~~ Meaning
  Meaning ~~ Accomplishment
  
  # Structural model - partial mediation
  AffectiveTemperament ~ a*CharacterStrength
  Wellbeing ~ c_prime*CharacterStrength + b*AffectiveTemperament
  
  # Define direct, indirect, and total effects
  indirect := a*b
  total := c_prime + (a*b)
'

# ================= SECTION 5: FITTING STRUCTURAL MODELS =================

# Fit Direct Effects Model
tryCatch({
  fit_direct <- sem(direct_model, data = data, missing = "fiml")
  summary_direct <- summary(fit_direct, fit.measures = TRUE, standardized = TRUE)
  cat("\nDIRECT EFFECTS MODEL:\n")
  print(summary_direct)
}, error = function(e) {
  cat("Error fitting Direct Effects model:", e$message, "\n")
})

# Fit Full Mediation Model
tryCatch({
  fit_full_mediation <- sem(full_mediation_model, data = data, missing = "fiml")
  summary_full_mediation <- summary(fit_full_mediation, fit.measures = TRUE, standardized = TRUE)
  cat("\nFULL MEDIATION MODEL:\n")
  print(summary_full_mediation)
}, error = function(e) {
  cat("Error fitting Full Mediation model:", e$message, "\n")
})

# Fit Partial Mediation Model
tryCatch({
  fit_partial_mediation <- sem(partial_mediation_model, data = data, missing = "fiml")
  summary_partial_mediation <- summary(fit_partial_mediation, fit.measures = TRUE, standardized = TRUE)
  cat("\nPARTIAL MEDIATION MODEL:\n")
  print(summary_partial_mediation)
}, error = function(e) {
  cat("Error fitting Partial Mediation model:", e$message, "\n")
})

# ================= SECTION 6: MODEL COMPARISON =================

# Compare models if they were successfully fitted
if(exists("fit_direct") && exists("fit_full_mediation") && exists("fit_partial_mediation")) {
  # Compare fit indices
  fit_measures <- data.frame(
    Model = c("Direct Effects", "Full Mediation", "Partial Mediation"),
    ChiSq = c(fitMeasures(fit_direct, "chisq"), 
              fitMeasures(fit_full_mediation, "chisq"),
              fitMeasures(fit_partial_mediation, "chisq")),
    df = c(fitMeasures(fit_direct, "df"),
           fitMeasures(fit_full_mediation, "df"),
           fitMeasures(fit_partial_mediation, "df")),
    CFI = c(fitMeasures(fit_direct, "cfi"),
            fitMeasures(fit_full_mediation, "cfi"),
            fitMeasures(fit_partial_mediation, "cfi")),
    TLI = c(fitMeasures(fit_direct, "tli"),
            fitMeasures(fit_full_mediation, "tli"),
            fitMeasures(fit_partial_mediation, "tli")),
    RMSEA = c(fitMeasures(fit_direct, "rmsea"),
              fitMeasures(fit_full_mediation, "rmsea"),
              fitMeasures(fit_partial_mediation, "rmsea")),
    AIC = c(fitMeasures(fit_direct, "aic"),
            fitMeasures(fit_full_mediation, "aic"),
            fitMeasures(fit_partial_mediation, "aic")),
    BIC = c(fitMeasures(fit_direct, "bic"),
            fitMeasures(fit_full_mediation, "bic"),
            fitMeasures(fit_partial_mediation, "bic"))
  )
  
  cat("\nMODEL FIT COMPARISON:\n")
  print(fit_measures)
  
  # Compare Partial vs Full Mediation (nested models)
  anova_result <- anova(fit_full_mediation, fit_partial_mediation)
  cat("\nChi-Square Difference Test (Full vs. Partial Mediation):\n")
  print(anova_result)
  
  # Interpret the result
  if(anova_result$`Pr(>Chisq)`[2] < 0.05) {
    cat("\nThe chi-square difference test is significant (p <", anova_result$`Pr(>Chisq)`[2], ").")
    cat("\nThis suggests that the Partial Mediation model fits significantly better than the Full Mediation model.")
    cat("\nHypothesis H3 (full mediation) is NOT supported.\n")
  } else {
    cat("\nThe chi-square difference test is NOT significant (p =", anova_result$`Pr(>Chisq)`[2], ").")
    cat("\nThis suggests that the Full Mediation model is not significantly worse than the Partial Mediation model.")
    cat("\nAccording to the principle of parsimony, the Full Mediation model might be preferred.")
    cat("\nHypothesis H3 (full mediation) is supported.\n")
  }
}

# ================= SECTION 7: MEDIATION ANALYSIS - COMPLETELY FIXED =================

# Completely fixed mediation analysis section
if(exists("fit_partial_mediation")) {
  # Extract parameter estimates
  params <- parameterEstimates(fit_partial_mediation, standardized = TRUE)
  
  # Direct extraction of path coefficients without complex filtering
  # This is more reliable than using label-based extraction
  
  # Path a: CharacterStrength → AffectiveTemperament
  a_path_row <- which(params$lhs == "AffectiveTemperament" & 
                     params$rhs == "CharacterStrength" & 
                     params$op == "~")
  
  # Path b: AffectiveTemperament → Wellbeing
  b_path_row <- which(params$lhs == "Wellbeing" & 
                     params$rhs == "AffectiveTemperament" & 
                     params$op == "~")
  
  # Direct effect (c'): CharacterStrength → Wellbeing
  c_prime_row <- which(params$lhs == "Wellbeing" & 
                       params$rhs == "CharacterStrength" & 
                       params$op == "~")
  
  # Indirect effect (a*b)
  indirect_row <- which(params$lhs == "indirect" & params$op == ":=")
  
  # Total effect
  total_row <- which(params$lhs == "total" & params$op == ":=")
  
  # Extract values with proper error handling
  a_path <- if(length(a_path_row) > 0) params$est.std[a_path_row] else NA
  b_path <- if(length(b_path_row) > 0) params$est.std[b_path_row] else NA
  direct_effect <- if(length(c_prime_row) > 0) params$est.std[c_prime_row] else NA
  indirect_effect <- if(length(indirect_row) > 0) params$est.std[indirect_row] else NA
  total_effect <- if(length(total_row) > 0) params$est.std[total_row] else NA
  
  # Safely calculate proportion mediated
  cat("\nMEDIATION ANALYSIS RESULTS:\n")
  
  if(!is.na(a_path)) cat("Path a (CharacterStrength → AffectiveTemperament):", round(a_path, 3), "\n")
  if(!is.na(b_path)) cat("Path b (AffectiveTemperament → Wellbeing):", round(b_path, 3), "\n")
  if(!is.na(direct_effect)) cat("Direct effect (c'):", round(direct_effect, 3), "\n")
  if(!is.na(indirect_effect)) cat("Indirect effect (a*b):", round(indirect_effect, 3), "\n")
  if(!is.na(total_effect)) cat("Total effect (c' + a*b):", round(total_effect, 3), "\n")
  
  if(!is.na(indirect_effect) && !is.na(total_effect) && total_effect != 0) {
    prop_mediated <- indirect_effect / total_effect
    cat("Proportion mediated:", round(prop_mediated, 3), "\n")
  }
  
  # Bootstrap confidence intervals with robust error handling
  tryCatch({
    # Use a reasonable number of bootstrap samples
    fit_boot <- sem(partial_mediation_model, data = data, missing = "fiml",
                   se = "bootstrap", bootstrap = 500)
    
    # Get the confidence intervals
    boot_ci <- parameterEstimates(fit_boot, boot.ci.type = "perc", standardized = TRUE)
    
    # Extract confidence intervals for indirect effect
    indirect_ci_row <- which(boot_ci$lhs == "indirect" & boot_ci$op == ":=")
    
    if(length(indirect_ci_row) > 0) {
      indirect_ci_lower <- boot_ci$ci.lower[indirect_ci_row]
      indirect_ci_upper <- boot_ci$ci.upper[indirect_ci_row]
      
      cat("\nBootstrap 95% CI for standardized indirect effect: [", 
          round(indirect_ci_lower, 3), ", ", 
          round(indirect_ci_upper, 3), "]\n")
      
      if(!is.na(indirect_ci_lower) && !is.na(indirect_ci_upper)) {
        if(indirect_ci_lower > 0 && indirect_ci_upper > 0) {
          cat("The indirect effect is statistically significant (CI does not include zero).\n")
          cat("Hypothesis H2 (mediation) is supported.\n")
        } else if(indirect_ci_lower < 0 && indirect_ci_upper < 0) {
          cat("The indirect effect is statistically significant and negative (CI does not include zero).\n")
          cat("Hypothesis H2 (mediation) is supported, but the effect is negative.\n")
        } else {
          cat("The indirect effect is NOT statistically significant (CI includes zero).\n")
          cat("Hypothesis H2 (mediation) is NOT supported.\n")
        }
      }
    } else {
      cat("\nCould not find bootstrap CI for indirect effect.\n")
    }
  }, error = function(e) {
    cat("Error during bootstrapping:", e$message, "\n")
    cat("Assessing indirect effect without bootstrap:\n")
    
    # If bootstrapping fails, use normal theory test
    if(!is.na(indirect_effect)) {
      pvalue_row <- which(params$lhs == "indirect" & params$op == ":=")
      if(length(pvalue_row) > 0) {
        pvalue <- params$pvalue[pvalue_row]
        cat("Indirect effect p-value:", pvalue, "\n")
        
        if(pvalue < 0.05) {
          cat("The indirect effect is statistically significant (p < 0.05).\n")
          cat("Hypothesis H2 (mediation) is supported.\n")
        } else {
          cat("The indirect effect is NOT statistically significant (p >= 0.05).\n")
          cat("Hypothesis H2 (mediation) is NOT supported.\n")
        }
      }
    }
  })
}

# ================= SECTION 8: CONCLUSION =================

cat("\nHYPOTHESIS TESTING SUMMARY:\n")

# Hypothesis 1: Character strengths are positively associated with well-being
if(exists("fit_direct")) {
  # Get the direct effect from the direct effects model
  direct_params <- parameterEstimates(fit_direct, standardized = TRUE)
  direct_effect_row <- which(direct_params$lhs == "Wellbeing" & 
                           direct_params$rhs == "CharacterStrength" & 
                           direct_params$op == "~")
  
  if(length(direct_effect_row) > 0) {
    direct_effect_h1 <- direct_params$est.std[direct_effect_row]
    direct_p_h1 <- direct_params$pvalue[direct_effect_row]
    
    cat("H1: Character strengths are positively associated with well-being.\n")
    if(!is.na(direct_effect_h1) && !is.na(direct_p_h1)) {
      if(direct_effect_h1 > 0 && direct_p_h1 < 0.05) {
        cat("   Result: SUPPORTED (β =", round(direct_effect_h1, 3), ", p <", round(direct_p_h1, 3), ")\n")
      } else {
        cat("   Result: NOT SUPPORTED (β =", round(direct_effect_h1, 3), ", p =", round(direct_p_h1, 3), ")\n")
      }
    }
  }
}

# Hypothesis 2: Affective temperament mediates the relationship
if(exists("indirect_effect") && !is.na(indirect_effect)) {
  cat("H2: Affective temperament mediates the relationship between character strengths and well-being.\n")
  
  # Check if we have bootstrap CI
  if(exists("indirect_ci_lower") && exists("indirect_ci_upper") && 
     !is.na(indirect_ci_lower) && !is.na(indirect_ci_upper)) {
    
    if(indirect_ci_lower > 0 && indirect_ci_upper > 0) {
      cat("   Result: SUPPORTED (indirect effect =", round(indirect_effect, 3), 
          ", 95% CI [", round(indirect_ci_lower, 3), ", ", round(indirect_ci_upper, 3), "])\n")
    } else if(indirect_ci_lower < 0 && indirect_ci_upper < 0) {
      cat("   Result: SUPPORTED with negative effect (indirect effect =", round(indirect_effect, 3), 
          ", 95% CI [", round(indirect_ci_lower, 3), ", ", round(indirect_ci_upper, 3), "])\n")
    } else {
      cat("   Result: NOT SUPPORTED (indirect effect =", round(indirect_effect, 3), 
          ", 95% CI [", round(indirect_ci_lower, 3), ", ", round(indirect_ci_upper, 3), "])\n")
    }
  } else {
    # Use p-value if bootstrap CI not available
    params <- parameterEstimates(fit_partial_mediation, standardized = TRUE)
    pvalue_row <- which(params$lhs == "indirect" & params$op == ":=")
    
    if(length(pvalue_row) > 0) {
      pvalue <- params$pvalue[pvalue_row]
      cat("   Result: ", ifelse(pvalue < 0.05, "SUPPORTED", "NOT SUPPORTED"), 
          " (indirect effect = ", round(indirect_effect, 3), ", p = ", round(pvalue, 3), ")\n", sep="")
    } else {
      cat("   Result: INCONCLUSIVE (indirect effect =", round(indirect_effect, 3), 
          ", no statistical test available)\n")
    }
  }
}

# Hypothesis 3: Full mediation
if(exists("anova_result")) {
  cat("H3: The effect of character strengths on well-being will be fully mediated by affective temperament.\n")
  if(anova_result$`Pr(>Chisq)`[2] < 0.05) {
    cat("   Result: NOT SUPPORTED (chi-square difference p =", round(anova_result$`Pr(>Chisq)`[2], 3), ")\n")
    cat("   The partial mediation model fits significantly better, suggesting both direct and indirect effects.\n")
  } else {
    cat("   Result: SUPPORTED (chi-square difference p =", round(anova_result$`Pr(>Chisq)`[2], 3), ")\n")
    cat("   The full mediation model is not significantly worse, suggesting complete mediation.\n")
  }
}

# ================= SECTION 9: ADDITIONAL CHECKS AND DISCUSSION =================

cat("\nMODEL FIT ASSESSMENT:\n")

# Character Strength model fit
if(exists("fit_char_strength")) {
  cs_fit <- fitMeasures(fit_char_strength, c("cfi", "tli", "rmsea", "srmr"))
  cat("Character Strength measurement model:\n")
  cat("   CFI = ", round(cs_fit["cfi"], 3),
      ", TLI = ", round(cs_fit["tli"], 3),
      ", RMSEA = ", round(cs_fit["rmsea"], 3),
      ", SRMR = ", round(cs_fit["srmr"], 3), "\n", sep="")
  
  if(cs_fit["cfi"] > 0.95 && cs_fit["tli"] > 0.95 && cs_fit["rmsea"] < 0.08 && cs_fit["srmr"] < 0.08) {
    cat("   Assessment: Good fit\n")
  } else if(cs_fit["cfi"] > 0.90 && cs_fit["tli"] > 0.90 && cs_fit["rmsea"] < 0.10 && cs_fit["srmr"] < 0.10) {
    cat("   Assessment: Acceptable fit\n")
  } else {
    cat("   Assessment: Poor fit - model needs revision\n")
  }
}

# Well-being model fit
if(exists("fit_wellbeing")) {
  wb_fit <- fitMeasures(fit_wellbeing, c("cfi", "tli", "rmsea", "srmr"))
  cat("Well-being measurement model:\n")
  cat("   CFI = ", round(wb_fit["cfi"], 3),
      ", TLI = ", round(wb_fit["tli"], 3),
      ", RMSEA = ", round(wb_fit["rmsea"], 3),
      ", SRMR = ", round(wb_fit["srmr"], 3), "\n", sep="")
  
  if(wb_fit["cfi"] > 0.95 && wb_fit["tli"] > 0.95 && wb_fit["rmsea"] < 0.08 && wb_fit["srmr"] < 0.08) {
    cat("   Assessment: Good fit\n")
  } else if(wb_fit["cfi"] > 0.90 && wb_fit["tli"] > 0.90 && wb_fit["rmsea"] < 0.10 && wb_fit["srmr"] < 0.10) {
    cat("   Assessment: Acceptable fit\n")
  } else {
    cat("   Assessment: Poor fit - model needs revision\n")
  }
}

# Affective Temperament model fit
if(exists("fit_temperament")) {
  # Check first if there are issues with the model
  neg_var <- FALSE
  
  temp_params <- parameterEstimates(fit_temperament, standardized = TRUE)
  var_rows <- which(temp_params$op == "~~" & temp_params$lhs == temp_params$rhs)
  if(any(temp_params$est[var_rows] < 0)) {
    neg_var <- TRUE
  }
  
  temp_fit <- fitMeasures(fit_temperament, c("cfi", "tli", "rmsea", "srmr"))
  cat("Affective Temperament measurement model:\n")
  cat("   CFI = ", round(temp_fit["cfi"], 3),
      ", TLI = ", round(temp_fit["tli"], 3),
      ", RMSEA = ", round(temp_fit["rmsea"], 3),
      ", SRMR = ", round(temp_fit["srmr"], 3), "\n", sep="")
  
  if(neg_var) {
    cat("   WARNING: Model has negative variances - serious specification issue\n")
    cat("   Assessment: Poor fit - model needs major revision\n")
  } else if(temp_fit["cfi"] > 0.95 && temp_fit["tli"] > 0.95 && temp_fit["rmsea"] < 0.08 && temp_fit["srmr"] < 0.08) {
    cat("   Assessment: Good fit\n")
  } else if(temp_fit["cfi"] > 0.90 && temp_fit["tli"] > 0.90 && temp_fit["rmsea"] < 0.10 && temp_fit["srmr"] < 0.10) {
    cat("   Assessment: Acceptable fit\n")
  } else {
    cat("   Assessment: Poor fit - model needs revision\n")
  }
}

# Final model fit
if(exists("fit_partial_mediation") && exists("fit_full_mediation")) {
  # Determine which model is preferred
  preferred_model <- if(anova_result$`Pr(>Chisq)`[2] < 0.05) "Partial Mediation" else "Full Mediation" 
  
  cat("\nFINAL MODEL ASSESSMENT:\n")
  cat("Preferred model based on hypothesis testing: ", preferred_model, "\n", sep="")
  
  if(preferred_model == "Partial Mediation") {
    pm_fit <- fitMeasures(fit_partial_mediation, c("cfi", "tli", "rmsea", "srmr"))
    cat("Partial Mediation model fit:\n")
    cat("   CFI = ", round(pm_fit["cfi"], 3),
        ", TLI = ", round(pm_fit["tli"], 3),
        ", RMSEA = ", round(pm_fit["rmsea"], 3),
        ", SRMR = ", round(pm_fit["srmr"], 3), "\n", sep="")
    
    if(pm_fit["cfi"] > 0.95 && pm_fit["tli"] > 0.95 && pm_fit["rmsea"] < 0.08 && pm_fit["srmr"] < 0.08) {
      cat("   Assessment: Good fit\n")
    } else if(pm_fit["cfi"] > 0.90 && pm_fit["tli"] > 0.90 && pm_fit["rmsea"] < 0.10 && pm_fit["srmr"] < 0.10) {
      cat("   Assessment: Acceptable fit\n")
    } else {
      cat("   Assessment: Poor fit - results should be interpreted with caution\n")
    }
  } else {
    fm_fit <- fitMeasures(fit_full_mediation, c("cfi", "tli", "rmsea", "srmr"))
    cat("Full Mediation model fit:\n")
    cat("   CFI = ", round(fm_fit["cfi"], 3),
        ", TLI = ", round(fm_fit["tli"], 3),
        ", RMSEA = ", round(fm_fit["rmsea"], 3),
        ", SRMR = ", round(fm_fit["srmr"], 3), "\n", sep="")
    
    if(fm_fit["cfi"] > 0.95 && fm_fit["tli"] > 0.95 && fm_fit["rmsea"] < 0.08 && fm_fit["srmr"] < 0.08) {
      cat("   Assessment: Good fit\n")
    } else if(fm_fit["cfi"] > 0.90 && fm_fit["tli"] > 0.90 && fm_fit["rmsea"] < 0.10 && fm_fit["srmr"] < 0.10) {
      cat("   Assessment: Acceptable fit\n")
    